package com.hyb.algorithm.data.struct.stack;

import java.util.Stack;

/**
 * @Author: huyanbing
 * @Date: 2021/9/24 11:18 上午
 * <p>
 * 20. 有效的括号
 * <p>
 * https://leetcode-cn.com/problems/valid-parentheses/
 */
public class ValidParentheses {

    public static void main(String[] args) {
        String s = "()[]{}";

        ValidParentheses exe = new ValidParentheses();
        boolean ret = exe.isValid(s);

        System.out.println(ret);

    }


    public boolean isValid(String s) {
        int n = s.length();

        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < n; i++) {

            char ch = s.charAt(i);

            if (ch == '(' || ch == '{' || ch == '[') {
                stack.push(ch);
                continue;
            }


            if (ch == ')' && !stack.isEmpty() && stack.peek() == '(') {
                stack.pop();
            } else if (ch == '}' && !stack.isEmpty() && stack.peek() == '{') {
                stack.pop();
            } else if (ch == ']' && !stack.isEmpty() && stack.peek() == '[') {
                stack.pop();
            } else {
                return false;
            }
        }

        return stack.isEmpty();
    }
}
